const mongoose = require('mongoose')
const Schema = mongoose.Schema
let ObjectId = Schema.Types.ObjectId
const bcrypt = require('bcrypt')
const SALT_WORK_FACTOR = 10
// 创建模型
const UserSchema = new Schema({
  UserId: { type: ObjectId },
  username: { type: String, unique: true },
  password: String,
  createAt: { type: Date, default: Date.now() },
  lastLoginAt: { type: Date, default: Date.now() }
})

//每次存储数据时都要执行
UserSchema.pre('save', function(next){
  let user = this
  console.log(this)
  bcrypt.genSalt( SALT_WORK_FACTOR,(err,salt)=>{
      if(err) return next(err)
      bcrypt.hash(user.password,salt, (err,hash)=>{
          if(err) return next(err)
          user.password = hash
          next()
      }) 
  })
})

UserSchema.methods = {
  // 密码比对方法
  comparePassword: (_password, password) => {
    return new Promise((resolve, reject) => {
      bcrypt.compare(_password, password, (err, isMatch)=>{
        if(!err) resolve(isMatch)
        else reject(err)
      })
    })
  }
}
// 发布模型
mongoose.model('User', UserSchema)